package org.hive.vmware.client.service;

import java.util.Date;
import java.util.List;

import org.hive.vmware.client.model.VmCenterServerTreeFolder;
import org.hive.vmware.client.model.VmCenterServerVO;
import org.hive.vmware.client.model.VmGroupingVO;
import org.hive.vmware.client.model.VmVO;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class CachedVmwareService {

	private final VmwareServiceAsync vmwareService = GWT.create(VmwareService.class);
	private static CachedVmwareService cachedVmwareService = null;
	private CachedVmwareService() {}
	
	private VmCenterServerTreeFolder cachedCenterServerTreeFolder = null;
	private long expiryCenterServerTreeFolderCacheTime = 0;
	private long EXPIRY_TIME = 1000 * 60 * 5; // 5 minutes
	
	public static CachedVmwareService getInstance() {
		if (cachedVmwareService == null) {
			cachedVmwareService = new CachedVmwareService();
		}
		return cachedVmwareService;
	}
	
	public void loadVmCenterServers(final AsyncCallback<List<VmCenterServerVO>> callback) {
			vmwareService.loadVmCenterServers(callback);
	}

	public void saveVmCenterServers(List<VmCenterServerVO> vmCenterServerVOs, AsyncCallback<Boolean> callback) {
		vmwareService.saveVmCenterServers(vmCenterServerVOs, callback);
		expiryCenterServerTreeFolderCacheTime = 0; // recache
	}

	public void loadVmCenterFolder(final AsyncCallback<VmCenterServerTreeFolder> callback) {
		if (expiryCenterServerTreeFolderCacheTime < new Date().getTime()) {
			AsyncCallback<VmCenterServerTreeFolder> newCallback = new AsyncCallback<VmCenterServerTreeFolder>() {
	
				@Override
				public void onFailure(Throwable caught) {
					callback.onFailure(caught);
				}
				@Override
				public void onSuccess(VmCenterServerTreeFolder result) {
					cachedCenterServerTreeFolder = result;
					expiryCenterServerTreeFolderCacheTime = new Date().getTime() + EXPIRY_TIME;
					callback.onSuccess(result);
				}
			};
			vmwareService.loadVmCenterFolder(newCallback);
		} else {
			System.out.println("useing cachedCenterServerTreeFolder");
			callback.onSuccess(cachedCenterServerTreeFolder);
		}
		
	}
	
	public void loadVmGrouping(AsyncCallback<VmGroupingVO> callback) {
		vmwareService.loadVmGrouping(callback);
	}

	public void saveVmGrouping(VmGroupingVO group, AsyncCallback<Boolean> callback) {
		vmwareService.saveVmGrouping(group, callback);
	}

	public void revertVms(List<VmVO> vms, AsyncCallback<Boolean> callback) {
		vmwareService.revertVms(vms, callback);
	}
	
}
